﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;

namespace AiMoInGH.Connector
{
    class ScriptDllLoader : IDisposable
    {
        public ScriptDllLoader()
        {
            AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
        }

        Dictionary<string, Assembly> externalAssembliesDict = new Dictionary<string, Assembly>();
        public void LoadExternalAssemblies(string[] externalAssemblies, out string error)
        {
            error = "";
            externalAssembliesDict.Clear();
            foreach (string assembly in externalAssemblies)
            {

                try
                {
                    Assembly ass = Assembly.LoadFrom(assembly);
                    externalAssembliesDict[ass.FullName] = ass;
                }
                catch (Exception ex)
                {
                    error += $"\r\n    Load External Assembly Error {assembly}:\r\n        {ex.Message}";
                }
            }
        }

        Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
        {
            if (externalAssembliesDict.TryGetValue(args.Name, out Assembly assembly))
            {
                return assembly;
            }
            return null;
        }

        public GHAiMoExecutor LoadScriptDll(string dllPath, GHScriptSource scriptSource, out string error)
        {
            if (File.Exists(dllPath))
            {
                return GHAiMoExecutor.LoadFrom(dllPath, scriptSource, out error);
            }
            else
            {
                error = $"    Debug Error: Load dll is not existed:\n{dllPath}";
            }
            return null;
        }

        public void Dispose()
        {
            AppDomain.CurrentDomain.AssemblyResolve -= CurrentDomain_AssemblyResolve;
        }
    }
}
